package com.itboye.eweilisten.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.itboye.eweilisten.util.XPermissionUtils;
import com.itboye.eweilisten.util.loadingutil.LoadingDialog;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.network.NetState;
import com.itboye.eweilisten.volley.ResultEntity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 继承自该Fragment的类不需要findViewById，在onActivityCreated中调用super.onActivityCreated()
 *
 * @author Young
 */
public abstract class BaseFragment extends Fragment implements View.OnClickListener{
    int states;
    LoadingDialog progressDialog = null;
    //   private PushAgent mPushAgent;
    public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
            .getName() + "_unknown";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
        // mPushAgent = PushAgent.getInstance(getActivity());
        // mPushAgent.enable();
        // mPushAgent.onAppStart();
        smartInject(getView());
        progressDialog = new LoadingDialog();
        onMyActivityCreated();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    protected void smartInject(View view) {
        try {
            Class<? extends Fragment> clz = getClass();
            while (clz != BaseFragment.class) {
                Field[] fs = clz.getDeclaredFields();
                Resources res = getResources();
                String packageName = getActivity().getPackageName();
                for (Field field : fs) {
                    if (!View.class.isAssignableFrom(field.getType())) {
                        continue;
                    }
                    int viewId = res.getIdentifier(field.getName(), "id",
                            packageName);
                    if (viewId == 0)
                        continue;
                    field.setAccessible(true);
                    try {
                        View v = view.findViewById(viewId);
                        field.set(this, v);
                        Class<?> c = field.getType();
                        Method m = c.getMethod("setOnClickListener",
                                View.OnClickListener.class);
                        m.invoke(v, this);
                    } catch (Throwable e) {
                    }
                    field.setAccessible(false);

                }

                clz = (Class<? extends Fragment>) clz.getSuperclass();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        XPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * @param data
     * @return 2016-4-23 hebidu
     */
    public ResultEntity handlerError(Object data) {
        ResultEntity result = (ResultEntity) data;
        if (result == null) {
            result = new ResultEntity("-1", "数据格式错误!~", data);
            return result;
        }

        if (result.hasError()) {

            if (result.getMsg().contains("java.net.UnknownHostException")) {
                MAlert.alert("请连接网络", Gravity.TOP);
            } else {
                MAlert.alert(result.getMsg(), Gravity.TOP);
            }
            result.setEventType(EVENT_TYPE_UNKNOWN);
            return result;
        }

        return result;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(initView(), null);
    }

    public abstract int initView();

    public abstract void onMyActivityCreated();

    /**
     * 显示进度对话框,带有消息 flag 是否可以取消
     */
    @SuppressLint("NewApi")
    public void showProgressDialog(String message, boolean flag) {
        if (progressDialog == null)
            return;
        setProgressDialogMessage(message);

        progressDialog.show(getActivity().getFragmentManager(), message);
        progressDialog.setCancelable(flag);

    }

    /**
     * 设置进度对话框消息
     *
     * @param message
     */
    public void setProgressDialogMessage(String message) {
        progressDialog.setMsg(message);
    }

    /**
     * 关闭进度对话框
     */
    @SuppressLint("NewApi")
    public void closeProgressDialog() {
        if (progressDialog != null) {
            if (progressDialog.getDialog().isShowing()) {
                progressDialog.dismiss();
            }
        }
    }

    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        return false;
    }

    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);
    }


    public int ChangeToDP(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    public String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;

            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

}
